package com.anywhere.freightman.system.service.impl;

import com.anywhere.freightman.common.BaseMapper;
import com.anywhere.freightman.common.BaseService;
import com.anywhere.freightman.common.enumeration.CommonStatus;
import com.anywhere.freightman.common.enumeration.TokenType;
import com.anywhere.freightman.common.utils.TokenUtils;
import com.anywhere.freightman.system.dao.AccessTokenDao;
import com.anywhere.freightman.system.model.AccessToken;
import com.anywhere.freightman.system.service.IAccessTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.Weekend;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class AccessTokenService extends BaseService<AccessToken> implements IAccessTokenService {

    @Autowired
    private AccessTokenDao accessTokenDao;

    @Override
    public BaseMapper<AccessToken> getBaseDao() {
        return accessTokenDao;
    }

    @Override
    public Example getExample(AccessToken entity) {
        return Weekend.of(AccessToken.class);
    }

    @Override
    public AccessToken getByUserId(long userId) {
        return accessTokenDao.getByUserId(userId);
    }

    @Override
    public AccessToken insert(long userId) {
        return insert(userId, TokenType.USER);
    }

    @Override
    public AccessToken insert(long userId, TokenType type) {
        logout(userId, type);
        AccessToken model = new AccessToken();
        model.setUserId(userId);
        model.setToken(TokenUtils.getQRandomString(32));
        model.setStatus(CommonStatus.ENABLE);
        model.setCreateTime(new Date());
        model.setType(type);
        insert(model);
        return model;
    }

    @Override
    public AccessToken getByToken(String token) {
        return accessTokenDao.getByToken(token);
    }

    @Override
    public void logout(long userId, TokenType type) {
        List<AccessToken> tokenList = accessTokenDao.getListByUserId(userId);
        tokenList.forEach(this::delete);
    }
}
